<?php
/**
 * Created by PhpStorm.
 * User: 毛文科
 * Date: 2019-07-29
 * Time: 20:07
 */
namespace app\admin\model;

use think\facade\Db;

class MyChildren
{
    protected $data = [];
    protected $table = '';
    protected $child = false;
    public function setTable($table=null){
        if($table){
            $this->table = $table;
        }
        return $this;
    }
    public function setChild($child=true){
        $this->getchild = $child;
        return $this;
    }
    public function getDataTofalse($pid=0,$chengji=0,$where=[]){
        $data = Db::name($this->table);
        $data=$data->where('pid',$pid)
            ->where($where)
//            ->where('status',1)
            ->where('delete_time',0)
//            ->whereOr('delete_time',0)
            ->order('sort desc')
            ->select();
//        echo 'hahha';exit;
        foreach ($data as $key=>$value){
            $value['cheng'] = $chengji;
            $value['child'] = $this->getDataTofalse($value['id'],$chengji+1,$where);
            $data[$key] = $value;
        }
        return $data;
    }
    public function getDataTotrue($pid=0,$chengji=0,$where=[]){
        $data = Db::name($this->table);
        $data=$data->where('pid',$pid)
            ->where($where)
            ->where('delete_time',0)
            ->order('sort desc')
            ->select();
        foreach ($data as $key=>$value){
            $value['chengji'] = $chengji;
            if($count = Db::name($this->table)->where($where)->where('pid',$value['id'])->where('delete_time',0)->count()){
                $value['child'] = $count;
            }else{
                $value['child'] = 0;
            }
            $this->data = array_merge($this->data,[$value]);
            $this->getDataTotrue($value['id'],$chengji+1,$where);
        }
        return $data;
    }
    public function getData(){
        return $this->data;
    }
    public static function getDatas($table,$ischild=false,$where=[]){
        $obj = new MyChildren();
        $obj->setTable($table);
        if($ischild){
            return $obj->getDataTofalse($table,0,$where);
        }
        $obj->getDataTotrue($table,0,$where);
        return $obj->getData();
    }
}